using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Configuration;
using Slam.Activation;
using Microsoft.SharePoint.Administration;

namespace Slam.Features.SLAM
{

	/// <summary>
	/// The SLAM FeatureReceiver performs tasks for activating and deactivating SLAM.  By default,
	/// on activation SLAM attaches its event handlers to all configured Lists and Content Types and
	/// deactivation detaches those event handlers.
	/// </summary>
	/// 
	[Guid("9f331eeb-1ce7-4ac0-a2b9-76dc1477d3af")]
	public class SLAMEventReceiver : SPFeatureReceiver
	{
		/// <summary>
		/// FeaturedDeactivated is called when the SLAM feature is deactivated and in turn calls
		/// SLAM's IActivator.Deactivate.  By default Deactivate detaches event handlers from all configured
		/// Lists and Content Types.
		/// </summary>
		/// <param name="properties"></param>
		public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
		{
			if (ConfigurationManager.AppSettings != null && properties.Feature.Parent is SPSite)
			{
				SPSite parentSite = properties.Feature.Parent as SPSite;
				bool deactivate = true;
				try
				{
					ComponentService.ClearInstances();
				}
				catch
				{
					//if ClearInstances runs into a problem it is most likely that
					//the Configuration cannot be found, in which case we want to
					//allow the feature to deactivate but not run SLAM's Deactivate process.
					deactivate = false;
				}
				if (deactivate)
				{
					ComponentService.ClearInstances();
					IActivator activator = ComponentService.GetInstance<IActivator>();
					activator.Deactivate(parentSite.Url);

					//If activation fails we want it to throw all exceptions so that 
					//the user deactivating this feature will see them directly
				}
			}
		}
	}
}
